/**
 * @file        obs_logger.c
 *
 * @brief       OpenBSD system programming study material logging system
 *
 * @author      Kevin Zhang (kevin.misc.10@gmail.com)
 * @data        2012/12/23
 */

#include "obs_logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define LOGGER_FILE             "obs.log"
#define LOGGER_DEBUG_FILE       "obs_debug.log"
#define LOGGER_ERROR_FILE       "obs_error.log"
#define LOGGER_FILE_RW_MODE     "w+"

static FILE *g_logger_debug;
static FILE *g_logger_info;
static FILE *g_logger_warn;
static FILE *g_logger_error;
static int g_obs_logger_flag;

void
obs_logger_debug (char *log)
{
    int log_len;

    log_len = strlen(log);

    flockfile(stdout);
    if (LOGGER_STDIO == g_obs_logger_flag) {
        fprintf(stdout, "%s", log);
    }
    funlockfile(stdout);

    if (fwrite(log, sizeof(unsigned char), log_len, g_logger_debug)
        != log_len) {
        fprintf(stdout, "Error in fwrite()");
    }

    flockfile(g_logger_debug);
    if (g_logger_debug) {
        fprintf(g_logger_debug, "%s", log);
    }
    funlockfile(g_logger_debug);
}

int
obs_logger_init(void)
{
    g_obs_logger_flag = LOGGER_STDIO;

    g_logger_debug = fopen(LOGGER_DEBUG_FILE, LOGGER_FILE_RW_MODE);
    if (!g_logger_debug) {
        fprintf(stderr, "Failed to open %s %s", LOGGER_DEBUG_FILE,
                LOGGER_FILE_RW_MODE);
        return -1;
    }

    g_logger_info = NULL;
    g_logger_warn = NULL;

    g_logger_error = fopen(LOGGER_ERROR_FILE, LOGGER_FILE_RW_MODE);
    if (!g_logger_error) {
        fprintf(stderr, "Failed to open %s %s", LOGGER_ERROR_FILE,
                LOGGER_FILE_RW_MODE);
        return -1;
    }

    return 0;
}

void
obs_logger_uninit(void)
{
    fclose(g_logger_info);
    fclose(g_logger_debug);
    fclose(g_logger_warn);
    fclose(g_logger_error);
}

FILE *
open_file(char *name)
{
    FILE *stream;
    register char *value;

    errno = 0;
    stream = fopen(name, "r");
    if (!stream) {
        fprintf(stderr, "%s(): Couldn't open file %s; %s\n", __func__, name,
                strerror(errno));
        //err(0, "ERROR");
        //exit(EXIT_FAILURE);
    }

    value = malloc(MEM_LEN);

    free(value);

    return stream;
}

void
obs_time(void)
{
}

void
test_obs_logger_open_log_file(void)
{
    (void)open_file(NULL);
}

